package com.vitabuybuy.tv.ui.mine.order

import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.net.loadingtype.LoadingType
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityOrderListBinding
import com.vitabuybuy.tv.dto.TabEntity
import com.library.common.toast.XToast
import com.library.common.util.DensityUtil
import com.library.common.widget.RecycleViewDivider
import com.vitabuybuy.tv.ui.cart.ConfirmOrderActivity
import com.vitabuybuy.tv.ui.cart.OrderPayActivity
import com.vitabuybuy.tv.ui.mine.order.adapter.OrderListAdapter
import com.vitabuybuy.tv.ui.mine.order.viewmodel.OrderViewModel
import com.vitabuybuy.tv.utils.EventCode
import com.vitabuybuy.tv.utils.KeyBoardUtils
import kotlinx.android.synthetic.main.activity_order_list.*
import java.util.*

/**
 * 作者：SimGa
 * 日期：2020/12/16
 * 时间：10:21
 * 包名：com.vitabuybuy.tv.ui.mine.order
 */
//    待支付  non-payment
//    代发货 paid
//    待收货 shipped
//    待评价 finished
//    已取消 canceled
//    已撤销 rejected
//    已完成 close
class OrderListActivity : BaseActivity<OrderViewModel, ActivityOrderListBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_order_list

    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var status: String? = ""
    private var pageNumber = 1
    private var keyWord = ""
    private val orderAdapter by lazy { OrderListAdapter() }

    override fun onGetBundle(bundle: Bundle?) {
        status = bundle?.getString("status")
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        mTabEntities.add(TabEntity(getString(R.string.all), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.wait_to_pay), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.wait_to_deliver), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.wait_to_receive), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.wait_to_comment), 0, 0))
        mTabLayout_1.setTabData(mTabEntities)
        when (status) {
            ALL -> mTabLayout_1.currentTab = 0
            WAITING_PAY -> mTabLayout_1.currentTab = 1
            WAITING_SEND -> mTabLayout_1.currentTab = 2
            WAITING_RECEIVER -> mTabLayout_1.currentTab = 3
            WAITING_COMMENT -> mTabLayout_1.currentTab = 4
        }
        listview.apply {
            adapter = orderAdapter
            layoutManager = LinearLayoutManager(mContext)
            addItemDecoration(RecycleViewDivider(mContext, DensityUtil.dip2px(10f)))
        }
    }

    override fun observeData() {
        viewModel.getOrderList(status, keyWord, pageNumber, 10)
        viewModel.orderList.observe(this, Observer {
            if (pageNumber == 1) {
                orderAdapter.mData.clear()
                orderAdapter.notifyDataSetChanged()
            }
            orderAdapter.addData(it)
            if (orderAdapter.mData.isEmpty()) {
                viewModel.statusView.set(LoadingType.SHOW_EMPTY)
            } else {
                viewModel.statusView.set(LoadingType.SHOW_CONTENT)
            }
        })
    }

    override fun eventHandling() {
        btnSearch.setOnClickListener {
            keyWord = etSearch.text.toString()
            pageNumber = 1
            viewModel.getOrderList(status, keyWord, pageNumber, 10)
            KeyBoardUtils.hideSoftKeyboard(mContext)
        }
        mTabLayout_1.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                status = when (position) {
                    1 -> WAITING_PAY
                    2 -> WAITING_SEND
                    3 -> WAITING_RECEIVER
                    4 -> WAITING_COMMENT
                    else -> ""
                }
                pageNumber = 1
                viewModel.getOrderList(status, keyWord, pageNumber, 10)
            }

            override fun onTabReselect(position: Int) {
            }
        })
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getOrderList(status, keyWord, pageNumber, 10)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber = 1
                viewModel.getOrderList(status, keyWord, pageNumber, 10)
            }
        })
        orderAdapter.onClickToPay = {
            OrderPayActivity.openActivity(
                mContext,
                orderAdapter.mData[it].id,
                orderAdapter.mData[it].goodsAmount,
                OrderPayActivity.FROM_PAY_ORDER
            )
        }
        orderAdapter.onClickCancel = {
            AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.reminder))
                .setMessage(getString(R.string.are_you_sure_cancel_order))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                    viewModel.cancelOrder(orderAdapter.mData[it].id)
                }
                .setNegativeButton(getString(R.string.cancel), null).create().show()
        }
        orderAdapter.onClickDelete = {
            AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.reminder))
                .setMessage(getString(R.string.are_you_sure_delete_order))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                    viewModel.deleteOrder(orderAdapter.mData[it].id, it)
                }
                .setNegativeButton(getString(R.string.cancel), null).create().show()
        }
        orderAdapter.onClickReminder = {
            viewModel.remindOrder(orderAdapter.mData[it].id)

        }
        orderAdapter.onClickConfirmReceive = {
            AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.reminder))
                .setMessage(getString(R.string.are_you_sure_confir_receiver))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                    viewModel.receiverOrder(orderAdapter.mData[it].id)
                }
                .setNegativeButton(getString(R.string.cancel), null).create().show()
        }
        orderAdapter.onClickBuyAgain = {
            ConfirmOrderActivity.openActivity(
                mContext,
                arrayListOf(orderAdapter.mData[it].id),
                ConfirmOrderActivity.BUY_AGAIN
            )
        }
        orderAdapter.onClickComment = {
            OrderCommentActivity.openActivity(
                mContext, orderAdapter.mData[it].itemList,
                orderAdapter.mData[it].store.name
            )
        }
        orderAdapter.onClickDeliver = {}
        orderAdapter.setOnItemClickListener { _, item, _ ->
            OrderDetailActivity.openActivity(mContext, item.id)
        }
        iv_back.setOnClickListener { finish() }
    }

    override fun onEvent(event: MessageEvent) {
        when (event.code) {
            EventCode.update_order_list -> {
                pageNumber = 1
                viewModel.getOrderList(status, keyWord, pageNumber, 10)
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                refresh.onLoad(msg.arg1)
            }
            0, 2, 3 -> {
                when (msg.arg1) {
                    1 -> XToast.success(getString(R.string.order_already_cancel))
                    2 -> XToast.success(getString(R.string.order_already_receiver))
                }
                pageNumber = 1
                viewModel.getOrderList(status, keyWord, pageNumber, 10)
            }
            4 -> {
                XToast.success(getString(R.string.already_remind_send))
            }
            5 -> {
                orderAdapter.removeAt(msg.arg1)
                XToast.success(getString(R.string.already_delete_order))
            }
        }
    }

    companion object {
        const val ALL = ""
        const val WAITING_PAY = "non-payment"
        const val WAITING_SEND = "paid"
        const val WAITING_RECEIVER = "shipped"
        const val WAITING_COMMENT = "finished"
        const val ALREADLY_CANCEL = "canceled"
        const val ALREADLY_REJECTED = "rejected"
        const val ALREADLY_CLOSE = "close"
        const val AFTER_SALE = ""
        fun openActivity(mContext: BaseActivity<*, *>, status: String) {
            mContext.startActivity(bundleOf(Pair("status", status)), OrderListActivity::class.java)
        }
    }

}